import React from 'react';
import {connect} from 'dva'
import moment from 'moment'
import Tools from 'utils/tools'

import { ListAbstract } from 'components/Abstract'

import { config } from 'utils'
const { scada } = config;
const {
  Token,
  Interval,
  StationIds,
  STypes,
  DTypes,
  SupplyId,
} = scada;

@connect(({index}) => ({...index}))
class RealTime extends React.Component {
    List = [
          {
            label: '今日供水量', icon: 'output', unit: 'm³', field: 'waterSupply',
            server: {
              type: 'index/queryStationList',
              payload: { type: 'Today' }
            }
          },
          {
            label: '瞬时流量', icon: 'flow', unit: 'm³/h', field: 'HD_flow',
            server: {
              type: 'index/queryHdStationList', payload: { type: 'TodaySupply', Stations: StationIds['supply'] }
            }
          },
          {
            label: '瞬时压力', icon: 'pressure', unit: 'Mpa', field: 'HD_YL',
            server: {
              type: 'index/queryScadeYLdata', payload: { type: "YL" }
            }
          }, {
            label: '余氯', icon: 'CI', unit: 'mg/l', field: 'HD_CI',
            fields: ["HD76_103_A6"]
          },
          {
            label: '浊度', icon: 'turbidity', unit: 'NTU', field: 'HD_NTU',
            fields: ["HD76_103_A3"]
          },
          {
            label: '盐酸液位', icon: 'HCl', unit: 'm', field: 'HD_HCl', fields: ['HD76_104_A5'],
            server: {
              type: 'index/queryHdStationList', payload: { type: 'TodayDrug', Stations: StationIds['drug'] }
            }
          },
          { label: '氯酸钠液位', icon: 'NaClO3', unit: 'm', field: 'HD_NaClO3', fields: ['HD76_104_A6'] }
        ]

        constructor(props) {
    super(props);

    let time;
    if ('defaultValue' in props) {
      time = props.defaultValue;
    }
    this.state = {
      time,
    };
  }

  componentDidMount() {
    this.init()
  }

  init = async () => {
    await this.setDateIndicators()
  }

  // 获取指标
  setDateIndicators = async () => {
    const { List } = this;
    List.map(ele => {
      const { server } = ele;
      if (server) this.queryServer(server);
    })
  }

  queryServer = async (server) => {
    const { time } = this.state;
    const startOfDay = moment(time).startOf('day');
    const endOfDay = moment(time).endOf('day');

    let { payload, type } = server;
    Object.assign(payload, { Token })
    // 供水量
    if(type === 'index/queryStationList'){
      const { supply } = StationIds;
      Object.assign(payload, {
        Interval,
        STypes,
        DTypes,
        Begin: startOfDay.unix(),
          End: endOfDay.unix(),
          StationId: supply.join(','),
      })
    }else if(type === 'index/queryHdStationList'){
      // 瞬时流量 、余氯：二氧化氯（余氯）、浊度：出厂水浊度
      Object.assign(payload, {
        From:0,
        Size:99999
      })
    }
    await this.props.dispatch(server);
  }

  countIncludesData = (source, fields, field = 'ObjId', value = 'Value') => {
    let result = 0;
    if(Array.isArray(source)){
      const filterArr = source.filter(v => fields.includes(v[field]))
      filterArr.map(val =>{
        result += val[value] *10000
      })
    }
    return result/10000;
  }

  render() {
    const { List, props } = this;

    // 供水量
    const waterSupply = Tools.countSupplyWater(props.SupplyWaterResourceToday);
    // 瞬时压力
    const HD_YL = Array.isArray(props.YLResource) && Array.isArray(props.YLResource[0].data) ? Tools.countYL(props.YLResource[0].data): null;

    // 瞬时流量 、 余氯：二氧化氯（余氯）、浊度：出厂水浊度
    let HD_flow = 0;
    let HD_CI = 0;
    let HD_NTU = 0;
    const HdStationData = props.HdStationListResourceTodaySupply;
    try {
      if(HdStationData && Array.isArray(HdStationData.Sensors)){
        const { Sensors } = HdStationData;
        // 从结果中取交集（从scade系统中获取字段类型，进行结果累加）
        // A. 瞬时流量[1#瞬时流量 、 2#临时流量]
        HD_flow = this.countIncludesData(Sensors, ["HD76_103_A1", "HD76_103_A2" ])
        // B. 二氧化氯（余氯）
        HD_CI = this.countIncludesData(Sensors, ["HD76_103_A6"])
        // C. 出厂水浊度
        HD_NTU = this.countIncludesData(Sensors, ["HD76_103_A3"])
      }
    } catch (error) {
      console.error(error)
    }
    // 盐酸液位、氯酸钠液位
    let HD_HCl = 0;
    let HD_NaClO3 = 0;
    const HdDrugData = props.HdStationListResourceTodayDrug;
    try {
      if(HdDrugData && Array.isArray(HdDrugData.Sensors)){
        const { Sensors } = HdDrugData;
        HD_HCl = this.countIncludesData(Sensors, ["HD76_104_A5" ])
        HD_NaClO3 = this.countIncludesData(Sensors, ["HD76_104_A6" ])
      }
    } catch (error) {
      console.error(error)
    }

    const dataSource = { waterSupply, HD_YL, HD_flow, HD_CI, HD_NTU, HD_HCl, HD_NaClO3 };
    return (<ListAbstract
      dataSource = {dataSource}
      columns={List}></ListAbstract>)
  }
}

export default RealTime;
